package com.zyw.zhuangdian.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

public class JWTUtil {

    // 过期时间1天

    public static final String AUTH_HEADER_KEY = "Authorization";

    public static String sign(String uid, String secret, Date exp) {
//        Date date = new Date(System.currentTimeMillis()+EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(secret);
        // 附带username信息
        return JWT.create()
                .withClaim("id", uid)
                .withExpiresAt(exp)
                .sign(algorithm);
    }

    public static boolean verify(String token, String uid, String secret) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("id", uid)
                    .build();
            verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    public static String getUserId(String token) {
        DecodedJWT decodedJWT = JWT.decode(token);
        return decodedJWT.getClaim("id").asString();
    }

    public static boolean isExpiration(String token){
        DecodedJWT decodedJWT = JWT.decode(token);
        Date exp = decodedJWT.getExpiresAt();
        return exp.before(new Date());
    }

}
